<template>
  <div>
    <el-form ref="loginFormRef" :rules="loginRules" :model="loginForm" size="large">
      <el-form-item prop="username">
        <el-input :maxlength="16" tabindex="1" autocomplete="on" v-model="loginForm.username" placeholder="请输入户名">
          <template #prefix>
            <el-icon color="#698DC2" size="18" class="el-input__icon">
              <user />
            </el-icon>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          :maxlength="16"
          size="large"
          v-model="loginForm.password"
          type="password"
          placeholder="请输入密码"
          show-password
          tabindex="2"
          autocomplete="on"
        >
          <template #prefix>
            <el-icon color="#698DC2" size="18" class="el-input__icon">
              <lock />
            </el-icon>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item prop="code">
        <div class="yzm">
          <div class="yzm-left">
            <el-input size="large" :maxlength="4" v-model="loginForm.code" placeholder="请输入验证码" tabindex="3"> </el-input>
          </div>
          <div @click="getCaptcha()" class="yzm-right">
            <img :src="'data:image/png;base64,' + captchaImage" alt="" />
          </div>
        </div>
      </el-form-item>
    </el-form>
    <div class="login-btn">
      <el-button size="large" type="primary" :loading="loading" @click="login(loginFormRef)"> 登录 </el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onBeforeUnmount } from "vue";
import { useRouter } from "vue-router";
import { HOME_URL } from "@/config";
import { getTimeState } from "@/utils";
import { Login } from "@/api/interface";
import { ElMessage, ElNotification } from "element-plus";
import { loginApi } from "@/api/modules/wl";
import { getCaptchaImage } from "@/api/modules/wl";
import { useUserStore } from "@/stores/modules/user";
import { useTabsStore } from "@/stores/modules/tabs";
import { useKeepAliveStore } from "@/stores/modules/keepAlive";
import { initDynamicRouter } from "@/routers/modules/dynamicRouter";
import { CircleClose, UserFilled } from "@element-plus/icons-vue";
import type { ElForm } from "element-plus";
import md5 from "md5";

const router = useRouter();
const userStore = useUserStore();
const tabsStore = useTabsStore();
const keepAliveStore = useKeepAliveStore();

type FormInstance = InstanceType<typeof ElForm>;
const loginFormRef = ref<FormInstance>();
const loginRules = reactive({
  username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  password: [{ required: true, message: "请输入密码", trigger: "blur" }],
  code: [{ required: true, message: "请输入验证码", trigger: "blur" }]
});
const captchaImage = ref("");

const loading = ref(false);
const loginForm = reactive<Login.ReqLoginForm>({
  username: "",
  password: "",
  code: "",
  uuid: ""
});

const login = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(async valid => {
    if (!valid) return;
    loading.value = true;
    try {
      // 1.执行登录接口
      const { rows, code, msg } = await loginApi({ ...loginForm });
      if (!(code === 200)) {
        ElMessage.error(msg);
        getCaptcha();
        return;
      }
      userStore.setToken(rows);
      userStore.setUserInfo({ username: loginForm.username });
      // userStore.setToken("12313213");

      // 2.添加动态路由
      await initDynamicRouter();
      // const res = await getUserInfo(data.userId);
      // userStore.setUserInfo(res.data);

      // 3.清空 tabs、keepAlive 数据
      tabsStore.setTabs([]);
      keepAliveStore.setKeepAliveName([]);

      // 4.跳转到首页
      router.push(HOME_URL);
      ElNotification({
        title: getTimeState(),
        message: "欢迎登录温岭智慧教育云平台",
        type: "success",
        duration: 3000
      });
    } finally {
      loading.value = false;
    }
  });
};

// resetForm
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

onMounted(() => {
  getCaptcha();
  // 监听 enter 事件（调用登录）
  document.onkeydown = (e: KeyboardEvent) => {
    e = (window.event as KeyboardEvent) || e;
    if (e.code === "Enter" || e.code === "enter" || e.code === "NumpadEnter") {
      if (loading.value) return;
      login(loginFormRef.value);
    }
  };
});

function getCaptcha() {
  getCaptchaImage().then(res => {
    console.log("res", res);
    loginForm.uuid = res.rows.uuid;
    captchaImage.value = res.rows.img;
    console.log("captchaImage", "data:image/png;base64," + captchaImage.value);
    // ElMessage.success("验证码已更新");
  });
}

onBeforeUnmount(() => {
  document.onkeydown = null;
});
</script>

<style scoped lang="scss">
@import "../index";
</style>
